from urllib.error import URLError
import feedparser
# https://feedparser.readthedocs.io/en/latest/
from config import YT_CHANNEL_ID


class CheckFeed:
    def __init__(self):
        # self.url = f"https://www.youtube.com/feeds/videos.xml?channel_id={YT_CHANNEL_ID}"
        self.url = f"https://vid.puffyan.us/feed/channel/{YT_CHANNEL_ID}"
        self.title = self._get_info()

    def read(self):
        list_of_videos = []
        try:
            feed = feedparser.parse(self.url)
            for entry in feed.entries:
                list_of_videos.append({
                    "id": entry["yt_videoid"],
                    "link": entry["link"],
                    "title": entry["title"]
                })
            return list_of_videos
        except URLError:
            return []

    def _get_info(self):
        try:
            feed = feedparser.parse(self.url)
            return feed['channel']['title']
        except KeyError:
            raise Exception('You are provide not valid feed url. Check FEED_URL in config.py')
        except URLError:
            raise Exception('URL. Check FEED_URL in config.py')
